import {defineStore} from 'pinia'
import {ref, computed} from 'vue'
import {useUserStore} from '@/stores/userStore.js'
import {insertCartAPI, getCartAPI, delCartAPI} from '@/apis/cart.js'

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    const cartList = ref([])

    // 更新购物车
    const updateCart = async () => {
        const res = await getCartAPI()
        cartList.value = res.result
    }

    // 添加购物车
    const addCart = async (goods) => {
        if (isLogin.value) {
            const {skuId, count} = goods
            await insertCartAPI({skuId, count})
            await updateCart()

        } else {
            const item = cartList.value.find(item => item.skuId === goods.skuId)
            if (item) {
                item.count += goods.count
            } else {
                cartList.value.push(goods)
            }
        }


    }

    // 删除购物车
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartAPI([skuId])
            await updateCart()
        } else {
            cartList.value = cartList.value.filter(item => item.skuId !== skuId)
        }
    }

    // 修改选中属性
    const changeSelected = (skuId, selected) => {
        const item = cartList.value.find(item => item.skuId === skuId)
        if (item) {
            item.selected = selected
        }
    }

    // 清除购物车
    const clearCart = () => {
        cartList.value = []
    }

    // 使用计算属性计算购物车中商品总数
    const cartCount = computed(() => {
        return cartList.value.reduce((pre, item) => pre + item.count, 0)
    })

    // 使用计算属性计算购物车中商品总价
    const cartPrice = computed(() => {
        return cartList.value.reduce((pre, item) => pre + item.count * item.price, 0)
    })
    // 使用计算属性计算选中的商品数量
    const selectedCount = computed(() => {
        return cartList.value
            .filter(item => item.selected)
            .reduce((pre, item) => pre + item.count, 0)
    })
    // 使用计算属性计算选中的商品总价
    const selectedPrice = computed(() => {
        return cartList.value
            .filter(item => item.selected)
            .reduce((pre, item) => pre + item.count * item.price, 0)
    })

    // 使用计算属性计算购物车中商品是否是全选状态
    const isAll = computed(() => cartList.value.every(item => item.selected))


    return {
        cartList,
        cartCount,
        cartPrice,
        selectedCount,
        selectedPrice,
        isAll,
        addCart,
        delCart,
        changeSelected,
        clearCart,
        updateCart
    }
}, {
    // 持久化配置 存入ls
    persist: true
})